//
//  TEA_ChatViewController.swift
//  NewsItem
//
//  Created by mac on 2023/8/1.
//  Copyright © 2023 Kaka. All rights reserved.
//

import UIKit
import Kingfisher

class TEA_ChatViewController: BasicViewController,PixelWorldChatProtocol,UITextFieldDelegate,NaviBarHidden {

    var model:InfoUtil.initInfo?
    var targetId:String?{
        didSet{
            RT.getOtherUserInfoUrlInfoWith(userid: targetId ?? "") { info in
                self.model = info
                self.table.reloadData()
                if let url = URL(string: self.model?.headImage ?? "") {
                    self.headBtn.kf.setImage(with: url, for: .normal,placeholder: .init(named:"avarB"))
                }
                self.nameL.text = self.model?.name
            }
        }
    }
    
    let moreBtn = UIButton.initV(img: "icon_more 1")
    let returnBtn = UIButton.initV(img: "icon_return 2")
    let headBtn = UIButton.initV(img: "avarB")
    let nameL = UILabel.initV(.setTypeFace(14,type: .medium), text: "",textColor:mainColor)

    private lazy var descView: Custom_TextView = {
        let view = Custom_TextView()
        view.backgroundColor = .color(hexString: "#F8E2BC")
        view.textContainerInset = UIEdgeInsets(top: 10.Fit, left: 10.Fit, bottom: 10.Fit, right: 10.Fit)
        view.tintColor = .black
        view.textColor = .black
        view.returnKeyType = .done
        view.font = .setTypeFace(14,type: .medium)
        view.placeHolder = "Say something!"
        view.placeHolderColor = .color(hexString: "#BE9146")
        view.contentInset = .init(top: 0, left: 0, bottom: 0, right: 50.Fit)
        return view
    }()

    let sendB = UIButton.initV(font: .setTypeFace(14.Fit,type: .bold), text: "Send", img: "")
    let picB = UIButton.initV(img: "picture")
    let videoB = UIButton.initV(img: "videob 1")
    let giftB = UIButton.initV(img: "send_gift")
    
    private lazy var table: UITableView = {
        let view = UITableView(frame: .zero, style: .plain)
        view.separatorStyle = .none
        view.backgroundColor = .clear
        view.delegate = self
        view.dataSource = self
        view.showsVerticalScrollIndicator = false
        view.register(MessageCell.self, forCellReuseIdentifier: MessageCell.description())
        view.register(MessagePhotoCell.self, forCellReuseIdentifier: MessagePhotoCell.description())
        view.register(MessageGiftCell.self, forCellReuseIdentifier: MessageGiftCell.description())
        view.rowHeight = UITableView.automaticDimension
        return view
    }()
    /// 消息数据源
    private var messages: [PixelWorldChatMessageBodyModel] = []
    private var historyMessages: [[PixelWorldChatMessageBodyModel]] = []
    /// 最早一条消息的messageId，获取更多更早的消息使用
    private var lastMessageId: String?
    let bottomBackV = UIView.init(frame: .zero)
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        view.subviews {
            returnBtn
            moreBtn
            headBtn
            nameL
            table
            bottomBackV.subviews {
                descView
                picB
                sendB
                videoB
            }
            
        }
        returnBtn.size(40.Fit).top(StatusBarHeight).left(15.Fit)
        returnBtn.addAct {
            self.navigationController?.popViewController(animated: true)
        }
        moreBtn.size(40.Fit).top(StatusBarHeight).right(15.Fit)
        moreBtn.addAct {
            let page = Edit_Choose_Photo_Interface(type: .reportAndBlock(userId: self.targetId?.intValue ?? 0,personal: true))
            self.present(page, animated: true)
        }
        headBtn.size(40.Fit).top(StatusBarHeight)
        headBtn.setAllCorners(corner: 20.Fit)
        headBtn.Leading == returnBtn.Trailing + 15.Fit
        
        nameL.height(20.Fit)
        nameL.Leading == headBtn.Trailing + 10.Fit
        nameL.Trailing == moreBtn.Leading - 10.Fit
        nameL.CenterY == headBtn.CenterY
        
        bottomBackV.left(0).right(0).bottom(0).height(TabbarSafeBottomMargin + 50.Fit)
        bottomBackV.backgroundColor = .white

        picB.left(10.Fit).size(40.Fit).top(5.Fit)
        videoB.size(40.Fit).top(5.Fit)
        videoB.Leading == picB.Trailing + 5.Fit
        
        videoB.addAct {
            guard self.model != nil else {
                return
            }
            UIImageView.downloadWith(urlStr: self.model?.headImage ?? "") { img in
                let vc = TEA_VideoViewController()
                vc.peerStr = self.model?.id
                vc.isRecept = false
                vc.headImage = img
                vc.nameStr = self.model?.name
                vc.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
        
        giftB.addAct {
            let vc = GiftListViewController()
            vc.modalPresentationStyle = .overFullScreen
            vc.returnBlock { str in
                
                AgoraRTMClient.shared.sendHyMessage(.emoji, img: nil, content:str, userid: self.targetId ?? "", conversationID: self.targetId ?? ""){ result in
                    if result.isSuccess {
                        self.appendMessages(result.messageModels)
                    }
                    self.descView.resignFirstResponder()
                    self.descView.text = ""
                }

            }
            self.present(vc, animated: false)
        }
        
        
        descView.height(40.Fit).top(5.Fit).right(25.Fit)
        descView.Leading == videoB.Trailing + 10.Fit
        descView.setAllCorners(corner: 10.Fit)
        
        sendB.height(30.Fit).width(55.Fit)
        sendB.CenterY == descView.CenterY
        sendB.Trailing == descView.Trailing - 5.Fit
        sendB.backgroundColor = mainColor
        sendB.setAllCorners(corner: 5.Fit)
        sendB.addAct {
            guard self.descView.text?.count != 0 else {
                return
            }
            AgoraRTMClient.shared.sendHyMessage(.text, img: nil, content: self.descView.text ?? "", userid: self.targetId ?? "", conversationID: self.targetId ?? ""){ result in
                if result.isSuccess {
                    self.appendMessages(result.messageModels)
                    
                }
                self.descView.resignFirstResponder()
                self.descView.text = ""
            }
        }
        
        table.top(NavHeight + 15.Fit).right(0.Fit).left(0.Fit)
        table.Bottom == descView.Top - 10.Fit
        table.backgroundColor = .clear
        
        picB.addAct {
            let page = Edit_Choose_Photo_Interface(type: .photoPicker)
            page.chooseImageCompletion = { [weak self] image in
                AgoraRTMClient.shared.sendHyMessage(.image, img: image, content: "", userid: self?.targetId ?? "", conversationID: self?.targetId ?? ""){ result in
                    if result.isSuccess {
                        self?.appendMessages(result.messageModels)
                    }
                }
            }
            self.present(page, animated: true)
        }
        self.chat.newMessages { result in
            self.appendMessages(result.messageModels)
        }
        loadHistoryMessages()
        
        NotificationCenter.default.addObserver(forName: NSNotification.Name("BlockRefreshNotice"), object: nil, queue: nil) {[weak self] noti in
            self?.navigationController?.popViewController(animated: true)
        }

    }
    
    
    // 添加消息
    func appendMessages(_ messages: [PixelWorldChatMessageBodyModel]) {
        let currentModels = messages.filter({ $0.userID == self.targetId })
        if !currentModels.isEmpty {
            self.messages.append(contentsOf: currentModels)
            scrollToBottom()
        }
    }
    //TODO: - 滑动到底部
    func scrollToBottom() {
        self.table.reloadData()
        self.table.layoutIfNeeded()
        guard self.table.contentSize.height > self.table.bounds.size.height else {
            return
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            let index = self.messages.count - 1
            let indexPath = IndexPath(row: index < 0 ? 0 : index, section: 0)
            self.table.scrollToRow(at: indexPath, at: .bottom, animated: false)
        }
        print("scrollToBottom=====  ")
        print(self.messages.count)
    }

    // 获取历史消息
    func loadHistoryMessages() {
        let messages = chat.historyMessages(self.targetId ?? "")
        self.appendMessages(messages)
    }
    
}


extension TEA_ChatViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = messages[indexPath.row]
        switch model.messageBodyType {
        case .text, .video:
            let cell = tableView.dequeueReusableCell(withIdentifier: MessageCell.description(), for: indexPath) as! MessageCell
            cell.selectionStyle = .none
            cell.headImgStr = self.model?.headImage
            cell.msgModel = model
            return cell
        case .image:
            let cell = tableView.dequeueReusableCell(withIdentifier: MessagePhotoCell.description(), for: indexPath) as! MessagePhotoCell
            cell.selectionStyle = .none
            cell.headImgStr = self.model?.headImage
            cell.msgModel = model
            return cell
        case .emoji:
            let cell = tableView.dequeueReusableCell(withIdentifier: MessageGiftCell.description(), for: indexPath) as! MessageGiftCell
            cell.selectionStyle = .none
            cell.headImgStr = self.model?.headImage
            cell.msgModel = model
            return cell
        default:
            return UITableViewCell()
        }
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.messages.count
    }

}



class MessagePhotoCell: UITableViewCell {
    
    let headImg = UIImageView.initImgView(img: "avarB")
    let coverV = UIImageView.initImgView(img: "")

    var model:InfoUtil.convesationData?{
        didSet{
            if let url = URL(string: self.model?.headImg ?? "") {
                self.headImg.kf.setImage(with: url,placeholder: UIImage.init(named: "avarB"))
            }else{
                self.headImg.image = .init(named: "avarB")
            }
            
            if let url = URL(string: self.model?.content ?? "") {
                self.coverV.kf.setImage(with: url)
            }

            if msgModel?.sourceType == .sender{
                // 自己发送的
                headImg.isHidden = true
                coverV.snp.makeConstraints { make in
                    make.top.equalTo(10.Fit)
                    make.trailing.equalTo(-70.Fit)
                    make.width.equalTo(170.Fit)
                    make.height.equalTo(205.Fit)
                    make.bottom.equalTo(-10.Fit)
                }
            }else{
                
                headImg.isHidden = false
                headImg.snp.remakeConstraints { make in
                    make.size.equalTo(45.Fit)
                    make.top.equalTo(5.Fit)
                    make.leading.equalTo(15.Fit)
                }
                coverV.snp.makeConstraints { make in
                    make.top.equalTo(10.Fit)
                    make.leading.equalTo(70.Fit)
                    make.width.equalTo(170.Fit)
                    make.height.equalTo(205.Fit)
                    make.bottom.equalTo(-10.Fit)
                }

            }
        }
    }
    
    var headImgStr:String?

    var msgModel:PixelWorldChatMessageBodyModel?{
        didSet{
            if let url = URL(string: self.headImgStr ?? "") {
                self.headImg.kf.setImage(with: url,placeholder: UIImage.init(named: "avarB"))
            }
            if let url = URL(string: msgModel?.imageUrl ?? "") {
                self.coverV.kf.setImage(with: url)
            }
            if msgModel?.sourceType == .sender{
                // 自己发送的
                headImg.isHidden = true
                coverV.snp.makeConstraints { make in
                    make.top.equalTo(10.Fit)
                    make.trailing.equalTo(-15.Fit)
                    make.width.equalTo(170.Fit)
                    make.height.equalTo(205.Fit)
                    make.bottom.equalTo(-10.Fit)
                }
            }else{
                headImg.isHidden = false
                headImg.snp.remakeConstraints { make in
                    make.size.equalTo(45.Fit)
                    make.top.equalTo(5.Fit)
                    make.leading.equalTo(15.Fit)
                }
                coverV.snp.makeConstraints { make in
                    make.top.equalTo(10.Fit)
                    make.leading.equalTo(70.Fit)
                    make.width.equalTo(170.Fit)
                    make.height.equalTo(205.Fit)
                    make.bottom.equalTo(-10.Fit)
                }

            }
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        backgroundColor = .clear
        selectionStyle = .none
        
        contentView.addSubview(headImg)
        contentView.addSubview(coverV)
        
        headImg.setAllCorners(corner: 22.5.Fit)
        coverV.setAllCorners(corner: 22.Fit)
        coverV.contentMode = .scaleAspectFill
        coverV.backgroundColor = .clear
        
        headImg.snp.makeConstraints { make in
            make.size.equalTo(45.Fit)
            make.top.equalTo(5.Fit)
            make.leading.equalTo(15.Fit)
        }
        coverV.snp.makeConstraints { make in
            make.top.equalTo(10.Fit)
            make.leading.equalTo(70.Fit)
            make.width.equalTo(170.Fit)
            make.height.equalTo(205.Fit)
            make.bottom.equalTo(-10.Fit)
        }
        
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}


class MessageCell: UITableViewCell {
    
    let backV = UIView.init(frame: .zero)
    let headImg = UIImageView.initImgView(img: "")
    private var cL = UILabel.initV(.setTypeFace(14,type: .medium), text: "", textColor: .color(hexString: "#A7A7A7"))
    var model:InfoUtil.convesationData?{
        didSet{
            self.cL.text = self.model?.content
            if let url = URL(string: self.model?.headImg ?? "") {
                self.headImg.kf.setImage(with: url,placeholder: UIImage.init(named: "avarB"))
            }
            var width = screenWidth - 85.Fit
            let size = self.model?.content?.getStringSize(rectSize: .init(width: width, height: CGFloat(MAXFLOAT)), font: .setTypeFace(16,type: .bold))
            if self.cL.calculateMaxLines(width: width) == 1{
                width = (size?.width ?? 0) + 35.Fit
            }
            print("width=======  ")
            print(self.cL.calculateMaxLines(width: width))
            
            if model?.id == USEINFOMODEL.id{
                // 自己发送的
                headImg.snp.remakeConstraints { make in
                    make.size.equalTo(45.Fit)
                    make.top.equalTo(5.Fit)
                    make.trailing.equalTo(-15.Fit)
                }
                backV.snp.remakeConstraints { make in
                    make.top.equalTo(10.Fit)
                    make.bottom.equalTo(-10.Fit)
                    make.trailing.equalTo(-70.Fit)
                    make.width.equalTo(width)
                    make.leading.greaterThanOrEqualTo(15.Fit)
                    make.height.equalTo((size?.height ?? 0) + 25.Fit)
                }
                cL.snp.remakeConstraints { make in
                    make.top.equalTo(12.Fit)
                    make.bottom.equalTo(-12.Fit)
                    make.trailing.equalTo(-15.Fit)
                    make.leading.equalTo(15.Fit)
                }
                cL.textAlignment = .right
                cL.textColor = mainColor
                cL.numberOfLines = 0
                backV.backgroundColor = .color(hexString: "#EDF2DC")
            }else{
                
                headImg.snp.remakeConstraints { make in
                    make.size.equalTo(45.Fit)
                    make.top.equalTo(5.Fit)
                    make.leading.equalTo(15.Fit)
                }
                backV.snp.remakeConstraints { make in
                    make.top.equalTo(10.Fit)
                    make.bottom.equalTo(-10.Fit)
                    make.leading.equalTo(70.Fit)
                    make.trailing.lessThanOrEqualTo(-15.Fit)
                    make.width.equalTo(width)
                    make.height.equalTo((size?.height ?? 0) + 25.Fit)
                }
                cL.snp.remakeConstraints { make in
                    make.top.equalTo(12.Fit)
                    make.bottom.equalTo(-12.Fit)
                    make.leading.equalTo(15.Fit)
                    make.trailing.equalTo(-15.Fit)
                }
                cL.textAlignment = .left
                cL.textColor = .white
                backV.backgroundColor = mainColor

            }
        }
    }
    
    var headImgStr:String?
    var msgModel:PixelWorldChatMessageBodyModel?{
        didSet{
            self.cL.text = self.msgModel?.lastMessage
            if let url = URL(string: self.headImgStr ?? "") {
                self.headImg.kf.setImage(with: url,placeholder: UIImage.init(named: "avarB"))

            }
            var width = screenWidth - 35.Fit
            let size = self.msgModel?.lastMessage?.getStringSize(rectSize: .init(width: width, height: CGFloat(MAXFLOAT)), font: .setTypeFace(16,type: .bold))
            
            if self.cL.calculateMaxLines(width: width) == 1{
                width = (size?.width ?? 0) + 35.Fit
            }
            print("height===-=======  ")
            print(self.cL.calculateMaxLines(width: width))
            print(width)
            if msgModel?.sourceType == .sender{
                // 自己发送的
                headImg.isHidden = true
                backV.snp.remakeConstraints { make in
                    make.top.equalTo(10.Fit)
                    make.bottom.equalTo(-10.Fit)
                    make.trailing.equalTo(-15.Fit)
                    make.leading.greaterThanOrEqualTo(15.Fit)
                    make.width.equalTo(width)
                    make.height.equalTo((size?.height ?? 0) + 25.Fit)
                }
                cL.snp.remakeConstraints { make in
                    make.top.equalTo(12.Fit)
                    make.bottom.equalTo(-15.Fit)
                    make.trailing.equalTo(-15.Fit)
                    make.leading.equalTo(15.Fit)
                }
                cL.textAlignment = .right
                cL.textColor = titleColor
                backV.backgroundColor = .white
            }else{

                headImg.isHidden = false
                headImg.snp.remakeConstraints { make in
                    make.size.equalTo(45.Fit)
                    make.top.equalTo(5.Fit)
                    make.leading.equalTo(15.Fit)
                }
                backV.snp.remakeConstraints { make in
                    make.top.equalTo(10.Fit)
                    make.bottom.equalTo(-10.Fit)
                    make.leading.equalTo(70.Fit)
                    make.width.equalTo(width)
                    make.trailing.lessThanOrEqualTo(-15.Fit)
                    make.height.equalTo((size?.height ?? 0) + 25.Fit)
                }
                cL.snp.remakeConstraints { make in
                    make.top.equalTo(12.Fit)
                    make.bottom.equalTo(-12.Fit)
                    make.leading.equalTo(15.Fit)
                    make.trailing.equalTo(-15.Fit)
                }
                cL.textColor = mainColor
                backV.backgroundColor = .black
                cL.textAlignment = .left
            }
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        backgroundColor = .clear
        selectionStyle = .none
        
        contentView.addSubview(headImg)
        contentView.addSubview(backV)
        backV.addSubview(cL)

        headImg.setAllCorners(corner: 22.5.Fit)
        backV.setAllCorners(corner: 14.Fit)

        headImg.snp.makeConstraints { make in
            make.size.equalTo(45.Fit)
            make.top.equalTo(5.Fit)
            make.leading.equalTo(15.Fit)
        }
        backV.snp.makeConstraints { make in
            make.top.equalTo(10.Fit)
            make.bottom.equalTo(-10.Fit)
            make.leading.equalTo(70.Fit)
            make.trailing.equalTo(40.Fit)
        }
        cL.snp.makeConstraints { make in
            make.top.equalTo(12.Fit)
            make.bottom.equalTo(-12.Fit)
            make.leading.equalTo(15.Fit)
            make.trailing.equalTo(-20.Fit)
        }
        cL.numberOfLines = 0
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension UILabel {
   /// 字符串分行后获取每行的内容
   /// 通过富文本分行，然后通过CTframe获取每一行的内容
    func calculateMaxLines(width: CGFloat) -> Int {
        let maxSize = CGSize(width: width, height: CGFloat(Float.infinity))
        let charSize = font.lineHeight
        let text = NSString(string: self.text ?? "")
        let textSize = text.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, attributes: [.font: font as Any], context: nil)
        let lines = Int(textSize.height/charSize)
        return lines
    }
}

class MessageGiftCell: UITableViewCell {
    
    let headImg = UIImageView.initImgView(img: "avarB")
    let coverV = UIImageView.initImgView(img: "")
    let backV = UIView.init(frame: .zero)

    var headImgStr:String?
    var msgModel:PixelWorldChatMessageBodyModel?{
        didSet{
            if let url = URL(string: self.headImgStr ?? "") {
                self.headImg.kf.setImage(with: url,placeholder: UIImage.init(named: "avarB"))
            }
            self.coverV.image = UIImage(named:self.msgModel?.lastMessage ?? "")
            if msgModel?.sourceType == .sender{
                // 自己发送的
                headImg.isHidden = true
                backV.snp.remakeConstraints { make in
                    make.trailing.equalTo(-15.Fit)
                    make.top.equalTo(10.Fit)
                    make.width.equalTo(70.Fit)
                    make.height.equalTo(50.Fit)
                    make.bottom.equalTo(-10.Fit)
                }
                coverV.snp.makeConstraints { make in
                    make.top.equalTo(5.Fit)
                    make.trailing.equalTo(-15.Fit)
                    make.leading.equalTo(15.Fit)
                    make.size.equalTo(40.Fit)
                }
                backV.backgroundColor = .color(hexString: "#EDF2DC")
            }else{
                backV.snp.remakeConstraints { make in
                    make.top.equalTo(10.Fit)
                    make.leading.equalTo(70.Fit)
                    make.width.equalTo(70.Fit)
                    make.height.equalTo(50.Fit)
                    make.bottom.equalTo(-10.Fit)
                }
                headImg.isHidden = false
                headImg.snp.remakeConstraints { make in
                    make.size.equalTo(45.Fit)
                    make.top.equalTo(5.Fit)
                    make.leading.equalTo(15.Fit)
                }
                coverV.snp.makeConstraints { make in
                    make.top.equalTo(5.Fit)
                    make.trailing.equalTo(-15.Fit)
                    make.leading.equalTo(15.Fit)
                    make.size.equalTo(40.Fit)
                }
                backV.backgroundColor = mainColor
            }
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        backgroundColor = .clear
        selectionStyle = .none
        
        contentView.addSubview(headImg)
        
        contentView.addSubview(backV)
        backV.addSubview(coverV)
        backV.setAllCorners(corner: 14.Fit)
        headImg.setAllCorners(corner: 22.5.Fit)
        
        coverV.contentMode = .scaleAspectFill
        coverV.backgroundColor = .clear
        
        backV.snp.makeConstraints { make in
            make.top.equalTo(10.Fit)
            make.trailing.equalTo(-70.Fit)
            make.width.equalTo(100.Fit)
            make.height.equalTo(40.Fit)
        }
        
        headImg.snp.makeConstraints { make in
            make.size.equalTo(45.Fit)
            make.top.equalTo(5.Fit)
            make.leading.equalTo(15.Fit)
        }
        coverV.snp.makeConstraints { make in
            make.top.equalTo(10.Fit)
            make.leading.equalTo(70.Fit)
            make.width.equalTo(170.Fit)
            make.height.equalTo(205.Fit)
            make.bottom.equalTo(-10.Fit)
        }
        
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
